# -*- coding:utf-8 -*-
import datetime

import hashlib
import os
import stat
from ftplib import FTP
from wanbatvcom.settings import MEDIA_ROOT


def make_token(format_str, *args):
    md5 = hashlib.md5()
    md5.update(format_str.format(*args))
    return md5.hexdigest()


def upload_file(file_object, file_name=None, file_suffix=None, cd=MEDIA_ROOT, root_dir=None, mode='wb',
                chmod=stat.S_IRWXG | stat.S_IRWXO | stat.S_IRWXU):
    if not file_object:
        return False, "file对象为空，无法完成上传"

    file_dir = cd
    if root_dir:
        if not root_dir.startswith('/'):
            file_dir += '/'
        file_dir += root_dir

    if not os.path.exists(file_dir):
        os.makedirs(file_dir)

    # os.chmod(file_dir, chmod)

    if not mode:
        mode = 'wb'

    file_handler = None
    try:
        fn = file_object.name if not file_name else file_name
        if file_suffix:
            if not file_suffix.startswith('.'):
                file_suffix = '.' + file_suffix
            fn += file_suffix
        file_handler = open(file_dir + "/" + fn, mode)
        if file_object.multiple_chunks():
            for chunk in file_object.chunks():
                file_handler.write(chunk)
        else:
            file_handler.write(file_object.read())
    except Exception as e:
        return False, e.message, ''
    finally:
        file_object.close()
        if file_handler:
            file_handler.close()

    return True, (root_dir if root_dir else "") + "/" + fn, file_dir + "/" + fn


def save_text_to_file(content, file_name=None, file_suffix=None, cd=MEDIA_ROOT, root_dir=None, mode="w"):
    if not content or not file_name:
        return False, "无法保存文件，内容或者名字为空"

    file_dir = cd
    if root_dir:
        if not root_dir.startswith('/'):
            file_dir += '/'
        file_dir += root_dir

    if not os.path.exists(file_dir):
        os.makedirs(file_dir)

    if not mode:
        mode = 'w'
    try:
        fn = file_name
        if file_suffix:
            if not file_suffix.startswith('.'):
                file_suffix = '.' + file_suffix
            fn += file_suffix
        file_handler = open(file_dir + "/" + fn, mode)
        file_handler.write(content)
        file_handler.close()
    except Exception as e:
        return False, e.message

    return True, (root_dir if root_dir else "") + "/" + fn, file_dir + "/" + fn


def upload_to_ftp(local_name, remote_name=None, src_path=None, dest_path=None,
                  host=None, port=21, user=None, password=None, buffer_size=2*1024*1024,
                  callback=None):
    """
    将指定目录的本地文件通过FTP转移到远程目录上
    :param local_name: 本地文件名
    :param remote_name: 远程文件名
    :param src_path: 本地目录
    :param dest_path: 远程目录
    :param host: 主机地址
    :param port: 端口，默认21
    :param user: 用户名
    :param password: 密码
    :param buffer_size: 缓存大小，默认8MB
    :param callback:
    :return: True 存储成功，否则失败
    """
    if not local_name:
        return False, '文件名不能为空'
    if not host:
        return False, 'FTP主机不能为空'

    if not remote_name:
        remote_name = local_name

    try:
        ftp = FTP()
        ftp.connect(host, str(port))
        ftp.login(user, password)

        if dest_path:
            dirs = dest_path.split("/")
            if len(dirs):
                for d in dirs:
                    ls = ftp.nlst()
                    if d not in ls:
                        ftp.mkd(d)
                    ftp.cwd(d)

        local_file_name = os.path.join(src_path, local_name)
        file_handler = open(local_file_name, "rb")

        total_size = [0]
        total_size[0] = os.path.getsize(local_file_name)
        completed_size = [0]

        import logging
        logger = logging.getLogger("wanba")

        def cb(buf):
            block_size = len(buf)
            completed_size[0] += block_size
            completed_percent = (float(completed_size[0]) / total_size[0]) * 100
            print("current %d, total %d" % (completed_size[0], total_size[0]))
            logger.info(u'uploading... current %d, total %d' % (completed_size[0], total_size[0]))
            if callback and callable(callback):
                callback(block_size, completed_size[0], total_size[0], completed_percent)

        ftp.storbinary('STOR %s' % remote_name, file_handler, blocksize=buffer_size, callback=cb)
        ftp.quit()
        file_handler.close()

    except Exception as e:
        return False, str(e)

    return True, dest_path + "/" + remote_name


def strftime(dt_obj, fm='%Y-%m-%d %H:%M:%S'):
    return dt_obj.strftime(fm)


def strptime(dt_str, fm='%Y-%m-%d %H:%M:%S'):
    return datetime.datetime.strptime(dt_str, fm)
